package common.helper;

import common.utils.HttpUtils;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.math.RandomUtils;

public class LogHelper {

  private static final String LOG_SPLIT = " | ";

  private static String getLog(HttpServletRequest request, String requestStr, String responseStr,
      String action, long costTime) {
    String ip = (request.getHeader("X-Real-IP") != null) ? request
        .getHeader("X-Real-IP") : request.getRemoteAddr();
    String userAgent = request.getHeader("USER-AGENT");
    return getLogString(ip, action, userAgent,
        requestStr,
        responseStr, costTime);
  }

  public static String getLogWithRequestParam(HttpServletRequest request, String responseStr,
      String clzName, String methodName, long costTime) {
    String clzMethodName = String.format("%s.%s", getShortClzName(clzName), methodName);
    String requestString = HttpUtils.getQueryString(request.getParameterMap());
    return getLog(request, requestString, responseStr, clzMethodName, costTime);
  }

  private static String getShortClzName(String clzFullName) {
    int cutIndex = clzFullName.lastIndexOf(".");
    return clzFullName.substring(cutIndex + 1, clzFullName.length());
  }

  public static String getLogString(String ip, String action,
      String userAgent, String reqJSON, String respJSON, long costTime) {
    StringBuffer sb = new StringBuffer();
    sb.append(ip).append(LOG_SPLIT).append(reqJSON).append(LOG_SPLIT)
        .append(respJSON).append(LOG_SPLIT).append(action)
        .append(LOG_SPLIT).append(userAgent).append(LOG_SPLIT).append(costTime);
    return sb.toString();
  }

  public static String generateTraceId(Long timestamp) {
    Long random = RandomUtils.nextLong();
    return timestamp.toString() + random.toString();
  }

  public static String getLogString(String url, String request, String respJSON, long costTime) {
    StringBuffer sb = new StringBuffer();
    sb.append(url).append(LOG_SPLIT).append(request).append(LOG_SPLIT).append(respJSON)
        .append(LOG_SPLIT).append(costTime);
    return sb.toString();
  }
}
